﻿Imports OpenInsure.Common
Public Class DBInstall

#Region "Form Events"

    Private Sub EditConnectionButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EditConnectionButton.Click
        Dim DLG As Dialogs.SQLConnectionDialog
        If Me.ConnectionStringTextBox.Text.CompareTo("") <> 0 Then
            DLG = New Dialogs.SQLConnectionDialog(Me.ConnectionStringTextBox.Text)
        Else
            DLG = New Dialogs.SQLConnectionDialog
        End If
        DLG.Text = "Configure Deployment Connection"
        If DLG.ShowDialog <> DialogResult.OK Then
            Exit Sub
        Else
            Me.ConnectionStringTextBox.Text = DLG.DeploymentConnectionString
            Me.TargetDBTextBox.Text = DLG.TargetDatabase
        End If

    End Sub

    Private Sub ManifestBrowse_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ManifestBrowse_Button.Click
        Try
            Me.ManifestOpenFileDialog.Filter = My.Resources.DBInstall_OpenFileDialogExtentions
            Me.ManifestOpenFileDialog.DefaultExt = My.Resources.DBInstall_OpenFileDialogDefaultExt
            Me.ManifestOpenFileDialog.Title = My.Resources.DBInstall_OpenFileDialogTitle
            If Me.ManifestOpenFileDialog.ShowDialog(Me) = Windows.Forms.DialogResult.OK Then
                Me.ManifestPathTextBox.Text = Me.ManifestOpenFileDialog.FileName
            End If
        Catch ex As Exception
            Dialogs.ExceptionDialog.DisplayException(ex, Me)
        End Try
    End Sub

    Private Sub StartButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles StartButton.Click
        If FormDataIsOk() Then
            Try
                LockForm(True)
                'Spin up the deployment thread
                Deploy = New DoDatabaseDeployDelegate(AddressOf DoDatabaseDeploy)
                Deploy.BeginInvoke(AddressOf End_DoDatabaseDeploy, Nothing)
            Catch ex As Exception
                Dialogs.ExceptionDialog.DisplayException(ex, Me)
            End Try
        End If
    End Sub

#End Region
    Private Deploy As DoDatabaseDeployDelegate

    Private Delegate Function DoDatabaseDeployDelegate() As Boolean
    Private Delegate Sub LockFormDelegate(ByVal Lock As Boolean)

    Private Sub LockForm(ByVal Lock As Boolean)
        Try
            If Me.InvokeRequired Then
                Dim D As New LockFormDelegate(AddressOf LockForm)
                Dim O() As Object = {Lock}
                Me.Invoke(D, O)
            Else
                Me.ManifestLabel.Enabled = Not Lock
                Me.ManifestPathTextBox.Enabled = Not Lock
                Me.ManifestBrowse_Button.Enabled = Not Lock
                Me.ConnectionStringLabel.Enabled = Not Lock
                Me.ConnectionStringTextBox.Enabled = Not Lock
                Me.EditConnectionButton.Enabled = Not Lock
                Me.TargetDatabaseLabel.Enabled = Not Lock
                Me.TargetDBTextBox.Enabled = Not Lock
                Me.StartButton.Enabled = Not Lock
            End If
        Catch ex As Exception
            Throw New Exception(ex.Message, ex)
        End Try
    End Sub

    Private Function DoDatabaseDeploy() As Boolean
        Try
            AddHandler DatabaseDeploy.DeploymentMessage, AddressOf DeploymentMessage
            DatabaseDeploy.DeployDatabase(Me.ManifestPathTextBox.Text, Me.ConnectionStringTextBox.Text, Me.TargetDBTextBox.Text)
            If DatabaseDeploy.ErrorCount = 0 Then
                Return True
            Else
                Return False
            End If
        Catch ex As Exception
            Throw New Exception(ex.Message, ex)
        Finally
            RemoveHandler DatabaseDeploy.DeploymentMessage, AddressOf DeploymentMessage
        End Try
    End Function

    Private Sub End_DoDatabaseDeploy(ByVal Ar As IAsyncResult)
        Try
            Dim Success As Boolean = Deploy.EndInvoke(Ar)
            If Not Success Then
                MsgBox(My.Resources.DBInstall_DeployFailed, MsgBoxStyle.Exclamation, My.Resources.DBInstall_DeployCompleteTitle)
            Else
                MsgBox(My.Resources.DBInstall_DeploySuccessfull, MsgBoxStyle.Information, My.Resources.DBInstall_DeployCompleteTitle)
            End If
        Catch ex As Exception
            Dialogs.ExceptionDialog.DisplayException(ex, Me)
        Finally
            LockForm(False)
        End Try
    End Sub

    Private Function FormDataIsOk() As Boolean
        Dim FI As New IO.FileInfo(Me.ManifestPathTextBox.Text)
        'Check the Manifest Files
        If Not FI.Exists Then
            MsgBox(My.Resources.DBInstall_ManifestFileNotFound, MsgBoxStyle.Exclamation, My.Resources.DBInstall_ManifestFileNotFoundTitle)
            Return False
        End If
        'Test the connection.
        Dim con As New SqlClient.SqlConnection(Me.ConnectionStringTextBox.Text)
        Try
            con.Open()
            Using cmd As New SqlClient.SqlCommand("SELECT IS_SRVROLEMEMBER(N'serveradmin')", con)
                Dim Result As Object = cmd.ExecuteScalar
                If Result = 1 Then
                    Return True
                Else
                    MsgBox(My.Resources.DBInstall_NotsysAdmin, MsgBoxStyle.Exclamation, My.Resources.DBInstall_NotsysAdminTitle)
                    Return False
                End If
            End Using
        Catch ex As Exception
            MsgBox(My.Resources.DBInstall_InvalidConnection, MsgBoxStyle.Exclamation, My.Resources.DBInstall_InvalidConnectionTitle)
            Return False
        Finally
            Try
                con.Close()
            Finally
                con.Dispose()
            End Try
        End Try
        'Return true if we've gotten through all these Checks
        Return True
    End Function

    Private Sub ManifestPathTextBox_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ManifestPathTextBox.TextChanged
        Try
            If IO.File.Exists(ManifestPathTextBox.Text) Then

            End If
        Catch ex As Exception
            Dialogs.ExceptionDialog.DisplayException(ex, Me)
        End Try
    End Sub

    Private Sub DeploymentMessage(ByVal sender As Object, ByVal e As DatabaseDeployEventArgs)
        Dim Color As Drawing.Color = Color.Black
        Select Case e.MessageType
            Case MessageTypeEnum.Error
                Color = Drawing.Color.Red
            Case MessageTypeEnum.Warning
                Color = Drawing.Color.Yellow
        End Select
        AddMessage(e.Message, Color)
    End Sub

    Private Delegate Sub AddMessageDelegate(ByVal Message As String, ByVal Color As Drawing.Color)
    Private Sub AddMessage(ByVal Message As String, ByVal Color As Drawing.Color)
        If Me.ListView1.InvokeRequired Then
            Dim D As New AddMessageDelegate(AddressOf AddMessage)
            Dim O() As Object = {Message, Color}
            Me.ListView1.Invoke(D, O)
        Else
            Try
                Dim item As New ListViewItem(Now.ToString("MM/dd/yyyy hh:mm:ss"))
                item.SubItems.Add(Message)
                item.ForeColor = Color
                ListView1.Items.Add(item)
            Catch ex As Exception
                Dialogs.ExceptionDialog.DisplayException(ex, Me)
            End Try
        End If
    End Sub

    Private Sub DBInstall_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        My.Settings.Upgrade()
    End Sub
End Class
